package com.example.inboxdemo.component;

import com.example.inboxdemo.pojo.entity.PublishDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;

/**
 * 订阅用户消息
 *
 * @author hongqianli@dobest.com
 * @since 2022/3/25 下午5:44
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InboxBroadcastTopicListener implements MessageListener<PublishDTO> {
    private final RedissonClient redissonClient;

    @PostConstruct
    public void subscribe() {
        // 不同于个人消息需要订阅指定的topic，单个服务实例仅需订阅1个inbox_broadcast_msg_topic，即可实现广播消息的订阅
        redissonClient.getTopic("inbox_broadcast_msg_topic")
                .addListener(PublishDTO.class, this);
        log.info("订阅广播消息..");
    }

    /**
     * 监听到inbox_broadcast_msg_topic topic下有数据产生会进入此方法
     * @param channel
     * @param msg
     */
    @Override
    public void onMessage(CharSequence channel, PublishDTO msg) {
        // 遍历当前实例下所有的在线用户，为其广播消息
        for (Map.Entry<String, SseEmitter> entry : SseEmitterServer.onlineUserEmitters.entrySet()) {
            String userId = entry.getKey();
            SseEmitter emitter = entry.getValue();
            try {
                emitter.send(msg);
            } catch (IOException e) {
                log.info("发送站内信失败：{}，用户可能已下线", userId);
            }
        }
    }
}
